import React, { Component } from 'react';
import { observable } from 'mobx';
import { observer, inject } from "mobx-react";
import { Row, Col, Input, Select, DatePicker, Radio, Button, message, Modal } from 'antd';
import moment from 'moment';
import TabTitle from '@/components/TabTitle/TabTitle';
import ReactQuill from 'react-quill';
import OperationRecord from '@/components/OperationRecord/OperationRecord'
import stringToArray from '@/common/stringToArray';
import http from '@/common/http';
import 'react-quill/dist/quill.snow.css';
import './ArticleEdit.less'

const Option = Select.Option;
const RadioGroup = Radio.Group;
const { RangePicker } = DatePicker;
const confirm = Modal.confirm;

const modules = {
  toolbar: [
    [{ 'header': [1, 2, false] }],
    ['bold', 'italic', 'underline','strike', 'blockquote'],
    [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}],
    ['link', 'image', 'video'],
    ['clean']
  ],
}

@inject('rootStore') @observer
class ArticleEdit extends Component {
  @observable articleParam = {
    "advertisementAvailableEndTime": "",
    "advertisementAvailableStartTime": "",
    "advertisementCategory": "",
    "advertisementChargeType": 101,
    "advertisementCondition": "en",
    "advertisementPrice": "",
    "advertisementPublisher": "",
    "advertisementTitle": "",
    "advertisementTotalAmount": "",
    "article": {
      "ad": true,
      "authTime": "",
      "authUserId": 0,
      "author": "",
      "categoryId": 0,
      "closeAnAccount": 0,
      "content": "",
      "createUserId": 0,
      "delState": true,
      "description": "",
      "gmtCreate": "",
      "gmtModified": "",
      "id": 0,
      "imgUrls": "",
      "keywords": "",
      "likeClickCount": 0,
      "local": "",
      "nuLikeClickCount": 0,
      "press": "string",
      "publishTime": "",
      "readCount": 0,
      "settledAmount": 0,
      "settledTime": "",
      "soft": true,
      "source": "",
      "status": 0,
      "summarize": "",
      "title": "",
      "top": true,
      "type": 0,
      "videoUrls": ""
    },
    "id": 0
  }
  @observable articleName = 'Article Edit'
  @observable operationRecord = []

  state = {
    rageTime: []
  }

  componentDidMount() {
    const advertisementStore = this.props.rootStore.advertisementStore;

    if (!advertisementStore.adCategorySuccess) {
      advertisementStore.toGetAdsCategory();
    }

    if (this.props.match.params.type !== 'create') {
      this.toGetDetails()
      this.toGetOperation(this.props.match.params.type)
      this.articleName = 'Article Edit'
    } else {
      this.articleName = 'Article Create'
    }
  }

  toGetDetails = () => {
    const globalStore = this.props.rootStore.globalStore;
    const param = {
      advertorialId: this.props.match.params.type
    }

    globalStore.toShowLoding()
    http.get('/advertisement/getAdvertorialById', param)
    .then((response) => {
      globalStore.toHideLoading()
      if (response.success) {
        this.articleParam = response.data
      }
    })
  }

  toGetOperation = (id) => {
    const param = {
      articleId: id,
    }

    http.get('/news/articleOperate/page', param)
    .then((response) => {
      if (response.success) {
        this.operationRecord = response.data.dataList;
      }
    })
  }

  backToList = (props) => {
    props.history.goBack();
  }

  titleOnChange = (e) => {
    this.articleParam.advertisementTitle = e.target.value;
  }

  conditionOnChange = (e) => {
    this.articleParam.advertisementCondition = e.target.value
    this.articleParam.article.local = e.target.value
  }

  categoryOnChange = (value) => {
    this.articleParam.advertisementCategory = value.join()
  }

  publisherOnChange = (e) => {
    this.articleParam.advertisementPublisher = e.target.value
  }

  totalOnChange = (e) => {
    this.articleParam.advertisementTotalAmount = e.target.value
  }

  timeChange = (value, dateString) => {
    this.setState({
      rageTime: value
    })
  }

  availableTimeOnChange = (value) => {
    this.articleParam.advertisementAvailableStartTime = moment(value[0]).format();
    this.articleParam.advertisementAvailableEndTime = moment(value[1]).format();
  }

  chargeTypeOnChange = (e) => {
    this.articleParam.advertisementChargeType = e.target.value
  }

  chargePriceOnChange = (e) => {
    this.articleParam.advertisementPrice = e.target.value
  }

  richTextOnChange = (value) => {
    this.articleParam.article.content = value;
  }

  showRelaseConfirm = (props) => {
    const globalStore = this.props.rootStore.globalStore;
    const that = this

    confirm({
      title: 'Are you sure release this news?',
      content: 'You can reapprove it in unavailable list',
      okText: 'Confirm',
      cancelText: 'Cancel',
      centered: true,
      onOk() {
        globalStore.toShowLoding();
        http.post('/advertisement/createAdvertorial', that.articleParam)
        .then((response) => {
          if (response.success) {
            globalStore.toHideLoading()
            message.success('Success');
            setTimeout(() => {
              props.history.goBack();
            }, 1000)
          }
        })
      },
      onCancel() {
      },
    });
  }

  render() {
    const breadCrumb = ['News', 'News List', 'Edit']
    const advertisementStore = this.props.rootStore.advertisementStore;

    return (
      <div className="news-edit">
        <TabTitle
          title={this.articleName}
          breadCrumb={breadCrumb} />
        <div className="page-content edit-form mt132">
          <div className="edit-form-btn-group">
            <div className="left-group">
              <Button
                type="primary"
                className="edit-btn"
                onClick={() => this.showRelaseConfirm(this.props)}>Release</Button>
            </div>
            <div className="right-group">
              <Button
                type="primary"
                className="back-btn"
                onClick={() => this.backToList(this.props)}>Back</Button>
            </div>
          </div>
          <div className="form-details">
            <div className="details-msg-form article-edit">
              <Row>
                <Col span={24}>
                  <div className="flex-item">
                    <label className="key-title">Ad.condition:</label>
                    <RadioGroup
                      value={this.articleParam.advertisementCondition}
                      onChange={this.conditionOnChange}>
                      <Radio value="en">English</Radio>
                      <Radio value="zh">Chinese</Radio>
                    </RadioGroup>
                  </div>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <div className="flex-item">
                    <label className="key-title">Title:</label>
                    <Input
                      className="msg-item"
                      value={this.articleParam.advertisementTitle}
                      onChange={this.titleOnChange} />
                  </div>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <div className="flex-item mr20">
                    <label className="key-title">Category:</label>
                    <Select
                      className="msg-item"
                      mode="multiple"
                      placeholder="Please select"
                      value={stringToArray(this.articleParam.advertisementCategory)}
                      onChange={this.categoryOnChange}>
                      {
                        advertisementStore.adCategoryList.map((item, index) => {
                          return (
                            <Option
                              key={item.id}
                              >{item.name}</Option>
                          )
                        })
                      }
                    </Select>
                  </div>
                </Col>
                <Col span={12}>
                  <div className="flex-item">
                    <label className="key-title">Publisher:</label>
                    <Input
                      className="msg-item"
                      value={this.articleParam.advertisementPublisher}
                      onChange={this.publisherOnChange} />
                  </div>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <div className="flex-item mr20">
                    <label className="key-title">Total Amount:</label>
                    <div className="flex1">
                      <Input
                        className="msg-item"
                        addonBefore="₱"
                        value={this.articleParam.advertisementTotalAmount}
                        onChange={this.totalOnChange} />
                    </div>
                  </div>
                </Col>
                <Col span={12}>
                  <div className="flex-item">
                    <label className="key-title">Available Time:</label>
                    <div className="flex1">
                      <RangePicker
                        showTime={{ format: 'HH:mm' }}
                        format="YYYY-MM-DD HH:mm"
                        placeholder={['Start Time', 'End Time']}
                        value={this.state.rageTime}
                        onChange={this.timeChange}
                        onOk={this.availableTimeOnChange}
                      />
                    </div>
                  </div>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <div className="ad-item">
                    <label className="ad-title">Charge Type:</label>
                    <div className="ad-content">
                      <RadioGroup
                        value={this.articleParam.advertisementChargeType}
                        onChange={this.chargeTypeOnChange}>
                        <Radio value={102}>CPC</Radio>
                        <Radio value={101}>CPM</Radio>
                        <Radio value={201}>Month</Radio>
                      </RadioGroup>
                      <Input
                        className="msg-item"
                        addonBefore="₱"
                        value={this.articleParam.advertisementPrice}
                        onChange={this.chargePriceOnChange} />
                    </div>
                  </div>
                </Col>
              </Row>
            </div>
          </div>
          <div className="details-rich-text mt10">
            <ReactQuill
              modules={modules}
              value={this.articleParam.article.content}
              onChange={this.richTextOnChange} />
          </div>
          {
            this.operationRecord && this.operationRecord.length !== 0 ?
            <OperationRecord
              operationRecord={this.operationRecord} />
            :
            null
          }
        </div>
      </div>
    )
  }
}

export default ArticleEdit;
